<?php

$t = new compare('wiki.noA','noAnalyse/log.wiki.lex.noAnalyse.txt','noAnalyse/log.wiki.nolex.noAnalyse.txt');
$t->out();
// $t = new compare('imslex.noA','noAnalyse/log.imslex.lex.noAnalyse.txt','noAnalyse/log.imslex.nolex.noAnalyse.txt');
// $t->out();
// $t = new compare('nzz.noA','noAnalyse/log.nzz.lex.noAnalyse.txt','noAnalyse/log.nzz.nolex.noAnalyse.txt');
// $t->out();

class compare {
	
	
	function __construct($pre,$file1,$file2){
		
		echo "process ".$pre."\n";
			
		$this->pre = $pre;
		
		$this->items1 = $this->getItems($file1);
		$this->items2 = $this->getItems($file2);
		
		$this->diffing();
	}
	
	function getItems($file){
		$arr = array();
		
		echo $file."\n";
		
		if(!($handle = fopen("logs/".$file,"r"))) die("Konnte Datei nicht öffnen!\n");
		$key = "";
		$items = array();
		while(!feof($handle)) {
			$line = trim(fgets($handle));
			if(!preg_match('/[\^\+]+/',$line)){ // schließt Item
				if(!empty($key)){
					$arr[$key] = $items;
				}
				$key = trim($line);
				$items = array();
			} else {
				$items[] = trim($line);
			}
			
		}
		return $arr;	
	}
	
	function diffing(){
		$this->notThere = array();
		$this->notSame = array();
		$this->same = array();
		
		$old = array_keys($this->items1);
		foreach(array_keys($this->items2) as $entry){
			if(!in_array($entry,$old)){
				$this->notThere[] = $entry;
			} else {
				echo $entry."\n";
				if($this->analyzeItems($entry)){
					$this->same[] = $entry;
				} else{
					$this->notSame[] = $entry;
				}
			}
		}
	}
	
	function analyzeItems($name){
		if(empty($this->items1[$name]) && empty($this->items2[$name]))
			return true;
		foreach($this->items1[$name] as $oldAna){
			foreach($this->items1[$name] as $newAna){
				if($oldAna == $newAna)
					return true;
			}
		}
		return false;
	}
	
	function out(){
		echo count($this->notThere)." Analysen sind neu.\n";
		echo count($this->same)." Analysen sind gleich.\n";
		echo count($this->notSame)." Analysen sind unterschiedlich.\n";
		
		// Logdateien
		foreach(array("new"=>"notThere","same"=>"same","different"=>"notSame") as $file=>$var){
			$handle = fopen("logs/compare.".$this->pre.".".$file.".txt","w");
			foreach($this->{$var} as $item){
				if(!empty($item))
					fwrite($handle,$item."\n");
				else
					fwrite($handle,"\n");
			}
			fclose($handle);
		}
	}
	
}
?>